<template>
  <div>
    <!-- 搜索 --><!-- 新增出入库申请 -->
  <div style="height: 25px;line-height: 50px;margin: 15px 0; display: flex;
            justify-content: center;
            align-items: center;">
            
  <div style="height: 50px;line-height: 50px;margin-right: 10px">
    <el-button type="primary" @click="add">备件出/入库<i class="el-icon-circle-plus-outline"></i></el-button>
  </div>
    <el-input
      style="width: 200px;"
      clearable
      placeholder="请输入备件序列号"
      suffix-icon="el-icon-search"
      type="text"
      v-model="search">

    </el-input><el-button class="ml-5" type="primary" @click="load">搜索</el-button>
  </div>
  
<!-- 备件明细 -->
  <el-table
    :data="sparepartsData"
    style="width: 100%"
    v-loading="loading"
    :row-class-name="tableRowClassName">
    <el-table-column prop="sid" label="备件序列号" width="105px"></el-table-column>
    <el-table-column prop="name" label="备件名称（生产厂商+类型+型号）" width="120px"></el-table-column>
    <el-table-column prop="applicant" label="申请人" width="100px"></el-table-column>
    <el-table-column prop="category" label="出/入库" width="105px"
                        :filters="[{ text: '出库', value: '出库' },
                                    { text: '入库', value: '入库' }]"
                                    :filter-method="filterButton1"
                                    filter-placement="bottom-end">
      <template slot-scope="scope">
        <el-button style="margin: auto;" type="primary" round v-if="scope.row.category === '出库'">出库</el-button>
        <el-button style="margin: auto;" type="success" round v-else-if="scope.row.category === '入库'">入库</el-button>
      </template> 
    </el-table-column>
    <el-table-column prop="status" label="当前环节" width="80px"
                      :filters="[{ text: '待审批', value: '待审批' },
                       { text: '已完成', value: '已完成' }]"
                       :filter-method="filterButton"
                       filter-placement="bottom-end">
      <template slot-scope="scope">
        <el-button style="margin: auto;" type="warning" round v-if="scope.row.status === '待审批'">待审批</el-button>
        <el-button style="margin: auto;" type="info" round v-else-if="scope.row.status === '已完成'">已完成</el-button>
      </template>    
    </el-table-column>
    <el-table-column prop="location" label="备件所处位置" width="100px"></el-table-column>
    <el-table-column prop="date" label="备件进出日期" width="100px"></el-table-column>
    <el-table-column prop="uname" label="审批人"></el-table-column>
    <el-table-column prop="department" label="审批人部门"></el-table-column>
    <el-table-column prop="phone" label="联系方式" width="100px"></el-table-column>
    <el-table-column prop="remarks" label="备注" width="120px">
    </el-table-column>

    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button type="primary" style="margin: auto;" 
                      icon="el-icon-edit" v-if="scope.row.status === '待审批'"  
                      circle @click="handleEdit(scope.row)"/>
        <el-button type="success" style="margin: auto;" 
                      icon="el-icon-check" v-if="scope.row.status === '待审批'"  
                      circle @click="handlefinish(scope.row)"/>
        <el-button type="info" v-if="scope.row.status === '已完成'"
                      plain style="margin: auto;"
                      @click="handlefinish(scope.row)">
                      详细信息
          </el-button>
      </template>
    </el-table-column>
  </el-table>

  <div style=" padding:10px 0;display:  flex;
            justify-content: center ;
            align-items: center;">
    <el-pagination
      style=" position: absolute;margin: auto"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next"
      :pager-count="7"
      :total="total">
    </el-pagination>
  </div>

  <el-dialog
    :visible.sync="dialogVisible"
    width="30%">

    <el-form 
    :model="ruleForm" 
    :rules="rules" 
    ref="ruleForm" 
    label-width="100px" class="demo-ruleForm">
      <el-form-item  prop="button">
        <el-button  v-model="ruleForm.button" disabled>{{ this.ruleForm.button }}</el-button>
      </el-form-item>
      <el-form-item label="序列号" prop="sid">
        <el-input  v-model="ruleForm.sid"></el-input>
      </el-form-item>
      <el-form-item label="备件名称" prop="name" placeholder="请输入（生产厂商+类型+型号）">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="出/入库" prop="category">
        <el-radio-group v-model="ruleForm.category">
          <el-radio label="入库" ></el-radio>
          <el-radio label="出库" ></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备件所在位置" prop="location">
        <el-input v-model="ruleForm.location"></el-input>
      </el-form-item>
      <el-form-item label="备件进/出日期" required>
        <el-col :span="16">
          <el-form-item prop="date">
            <el-date-picker  value-format="yyyy-MM-dd" placeholder="选择日期" v-model="ruleForm.date" style="width: 100%;"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="备注" prop="remarks">
        <el-input type="textarea" v-model="ruleForm.remarks"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>

  <el-dialog
      title="备件单信息"
      :visible.sync="dialogVisible1"
      width="60%"
      height="50%">
      <span>
        <el-descriptions class="margin-top" :column="3"  border>
        <el-descriptions-item label="备件单号">{{ this.descriptions.sid }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{ this.descriptions.applicant }}</el-descriptions-item>
        <el-descriptions-item label="出/入库">{{ this.descriptions.category }}</el-descriptions-item>
        <el-descriptions-item label="当前环节">{{ this.descriptions.status }}</el-descriptions-item>
        <el-descriptions-item label="备件位置">{{ this.descriptions.location }}</el-descriptions-item>
        <el-descriptions-item label="备件进出日期">{{ this.descriptions.date }}</el-descriptions-item>
        <el-descriptions-item label="审批人">{{ this.descriptions.uname }}</el-descriptions-item>
        <el-descriptions-item label="审批人部门">{{ this.descriptions.department }}</el-descriptions-item>
        <el-descriptions-item label="审批人联系方式">{{ this.descriptions.phone }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ this.descriptions.remarks }}</el-descriptions-item>
      </el-descriptions>
      </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible1 = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible1 = false">确定</el-button>
  </span>
    </el-dialog>
</div>
</template>

<script>
import request from "../../utils/request";

export default {
  name: 'SparepartsQuery.vue',
  data(){
    return{
      search: '',
      dialogVisible: false,
      dialogVisible1: false,
      sparepartsData: [],
      descriptions: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      ruleForm: {
      },
      user: JSON.parse(localStorage.getItem('user')),
      rules: {
        sid: [
          { required: true, message: '请输入备件序列号', trigger: 'change' },
        ],
        name: [
          { required: true, message: '请输入备件名称', trigger: 'change' },
        ],
        category: [
          { required: true, message: '请选择出/入库', trigger: 'change' },
        ],
        location: [
          { required: true, message: '请输入备件出/入库位置', trigger: 'change' },
        ],
        date: [
          { required: true, message: '请输入备件出/入库日期', trigger: 'change' },
        ]
      },
      loading : true

  }
  },
  created() {
    this.load()
  },
  methods:{
    tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      },
    //格式化日期列
    dateFormatter(row,column){
      let datetime = row.entry;
      if(datetime){
        datetime = new Date(datetime);
        let y = datetime.getFullYear() + '-';
        let m = datetime.getMonth()+1 + '-';
        let d = datetime.getDate();
        return y + m + d;
      }
      return ''
    },
    //页面加载时，将数据传输给后端，后端数据渲染res.data.records到前端tableData
    load(){
      request.get("/sys/spareparts/selectAll",{
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        console.log(res)
        console.log(this.search)
        this.sparepartsData = res.data.records
        this.loading = false
        console.log(this.sparepartsData)
        this.total = res.data.total
      })
    },
    //新增按钮触发事件 添加记录弹窗
    add(){
      this.dialogVisible = true;
      this.ruleForm = {};
      this.ruleForm.button = "新建备件记录"
      this.ruleForm.status = "待审批"
    },
    //将弹窗内ruleForm表单数据传给后端，后端将数据
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.ruleForm.button == "修改信息"){ //表单中有工单号元素 则是执行更新操作
        request.put("/sys/spareparts/update",this.ruleForm).then(res =>{
          console.log(res);
          // console.log(this.ruleForm)
          if (res.code === '1'){
            this.$message({
              type: "success",
              message: "修改信息成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load() //刷新
          this.dialogVisible = false
        });
        this.load() //刷新
        this.dialogVisible = false
      }else { //新增
        request.post("/sys/spareparts/add",this.ruleForm).then(res =>{
          console.log(res);
          // console.log(this.ruleForm)
          if (res.code === '1'){
            this.$message({
              type: "success",
              message: "新增用户成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load() //刷新
          this.dialogVisible = false
        });
      }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    //重置新增 表单内容
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    filterButton(value, row) {
      return row.status === value;
    },
    filterButton1(value, row) {
      return row.category === value;
    },
    //表格编辑功能
    handleEdit(row){
      this.ruleForm = JSON.parse(JSON.stringify(row)) //与之前对象隔离开,避免浅拷贝问题
      this.ruleForm.button = "修改信息"
      this.dialogVisible = true;
      
      
    },
    //表格审批功能
    handlefinish(row){
      this.ruleForm = JSON.parse(JSON.stringify(row))
      switch(this.ruleForm.status){
        case '待审批':
      this.ruleForm.uname = this.user.name
      this.ruleForm.department = this.user.department
      this.ruleForm.phone = this.user.phone
      request.put("/sys/spareparts/finish",this.ruleForm).then(res=>{
        if (res.code === '1'){
          this.$message({
            type: "success",
            message: "审批成功"
          })
        } else {
          this.$message({
            type: "error",
            message: res.msg
          })
        }
        this.load()  //删除后重新加载
      })
        break;

        case '已完成':
        this.Form = JSON.parse(JSON.stringify(row)) //与之前对象隔离开,避免浅拷贝问题
        this.descriptions = this.Form
        this.dialogVisible1 = true
        break;
      } 
    },
    handleSizeChange(pageSize) {  //改变当前每页显示个数触发
      this.pageSize = pageSize;
        this.load()
    },
    handleCurrentChange(currentPage) {  //改变当前页码 触发
      this.currentPage = currentPage;
      this.load()
    }
  }

}
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
